import { getNotifyList } from '@/api/help';
import { showModal } from '@/utils/message';
import notifyHeader from '@/assets/help/notify_header.png';
import notifyBg from '@/assets/help/notify_bg.png';

let notifyTimer = null;
export const pollingNotify = () => {
  const PollingTime = 30000;
  if (notifyTimer) clearTimeout(notifyTimer);
  getNotifyList().then(res => {
    if (res.code === 200 && res.data) {
      const task = JSON.parse(JSON.stringify(res.data));
      const queue = Array.isArray(task) ? task : [task];
      notify(queue, PollingTime);
    } else {
      notifyTimer = setTimeout(() => {
        pollingNotify();
      }, PollingTime);
    }
  });
};
function notify(queue, PollingTime) {
  const curMsg = queue.shift();
  // console.log(curMsg);\
  if (!curMsg) { return; }
  showMsg(curMsg, () => {
    if (queue.length === 0) {
      notifyTimer = setTimeout(() => {
        pollingNotify();
      }, PollingTime);
    } else {
      notify(queue, PollingTime);
    }
  });
}
export function showMsg(msgData, callback, isPreview = false) {
  const cache = JSON.parse(localStorage.getItem('helpNotify') || '[]');
  if (!isPreview && cache.includes(msgData.id)) {
    if (callback) callback();
    return;
  }
  if (!isPreview && !cache.includes(msgData.id)) {
    cache.push(msgData.id);
    localStorage.setItem('helpNotify', JSON.stringify(cache));
  }
  let msg = msgData.content;
  if (msgData.title) {
    msg = `
    <div class="help-msg-main">
      <div class="help-msg-header" style="background-image: url(${notifyBg});">
        <div style="width: 319px;">${msgData.title}</div>
      </div>
      <img class="notify-icon" src="${notifyHeader}" />
      <div class="help-msg-content">${msg}</div>
    </div>
    `;
  }
  showModal(msg, '', {
    iconClass: 'none-icon',
    center: false,
    confirmButtonText: '确定',
    dangerouslyUseHTMLString: true,
    showClose: true,
    showCancelButton: false,
    customClass: 'help-notify-msg'
  }, true).then(() => {
    if (callback) callback();
  }).catch(() => {
    if (callback) callback();
  });
}
